package cn.lbd.auth.controller;

import cn.lbd.auth.core.Common;
import cn.lbd.auth.core.HttpResult;
import cn.lbd.auth.entity.User;
import cn.lbd.auth.security.JwtAuthenticatioToken;
import cn.lbd.auth.security.JwtUserDetails;
import cn.lbd.auth.security.UserDetailsServiceImpl;
import cn.lbd.auth.service.AdminService;
import cn.lbd.auth.utils.SecurityUtils;
import cn.lbd.auth.vo.LoginBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 登录接口（普通验证码适配）
     */
    @RequestMapping(value = "/login")
    public HttpResult login(@RequestBody LoginBean loginBean, HttpServletRequest request){
        log.info("10030认证微服务被远程调用，开始登录....");
        String username = loginBean.getUsername();
        String password = loginBean.getPassword();
        User user = adminService.getOperatorById(Integer.parseInt(username));
        if (null == user) {
            return HttpResult.error("账号不存在或不可用！");
        } else {
            try {
                JwtAuthenticatioToken token = SecurityUtils.login(request, username, password, authenticationManager);
                String tokenKey = user.getOperatorId() + token.getToken() + ":JWT";
                redisTemplate.opsForValue().set(tokenKey,token.getToken(), Common.expire, TimeUnit.MILLISECONDS);
                return HttpResult.ok(token);
            } catch (BadCredentialsException e) {
                return HttpResult.error("密码错误！");
            }
        }
    }
}
